package pagination

import (
	"github.com/jinzhu/gorm"
)

// Param struct
type Param struct {
	DB      *gorm.DB
	Page    int
	Limit   int
	OrderBy []string
	Debug   bool
}

// Pagination struct
type Pagination struct {
	db          *gorm.DB
	TotalRecord int         `json:"total"`
	List        interface{} `json:"list"`
	Limit       int         `json:"limit"`
	Page        int         `json:"page"`
	offset      int
}

// Pagging func
func Page(param *Param) (*gorm.DB, *Pagination) {
	db := param.DB

	if param.Debug {
		db = db.Debug()
	}
	if param.Page < 1 {
		param.Page = 1
	}
	if param.Limit == 0 {
		param.Limit = 10
	}
	if len(param.OrderBy) > 0 {
		for _, o := range param.OrderBy {
			db = db.Order(o)
		}
	}

	done := make(chan bool, 1)
	var pagination Pagination
	var count int
	var offset int

	go countRecords(db, done, &count)

	if param.Page == 1 {
		offset = 0
	} else {
		offset = (param.Page - 1) * param.Limit
	}

	db = db.Limit(param.Limit).Offset(offset)
	<-done

	pagination.TotalRecord = count
	pagination.Page = param.Page

	pagination.offset = offset
	pagination.Limit = param.Limit
	pagination.db = db

	return db, &pagination
}

func countRecords(db *gorm.DB, done chan bool, count *int) {
	db.Count(count)
	done <- true
}
